package com.gulimall.common.validator.customValidAnnotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * ListValue注解自定义校验器
 */
public class ListValueChecker implements ConstraintValidator<ListValue, Integer> {

    private Set<Integer> set = new HashSet<>();

    /**
     * 初始化方法
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] value = constraintAnnotation.value();
        if (value.length > 0) {
            for (Integer i : value) {
                set.add(i);
            }
        }
    }

    /**
     * 判断是否校验成功
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return 若校验字段的值在指定数组中，则返回true；反之返回false
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return set.contains(value);
    }
}
